package com.cloud.mall.config.component;

import com.cloud.mall.base.BaseResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class AuthExceptionEntryPoint implements AuthenticationEntryPoint
{

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json");
       // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), error(request,authException));
        } catch (Exception e) {
            throw new ServletException();
        }
    }

    private BaseResponse error(HttpServletRequest request, AuthenticationException authException){
        Throwable cause = authException.getCause();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("path", request.getServletPath());
        map.put("timestamp", String.valueOf(new Date().getTime()));
        map.put("message", authException.getMessage());
        if(cause instanceof InvalidTokenException) {
         return    BaseResponse.unauthorized(map);
        }else{
            return   BaseResponse.checkAuthorized(map);
        }
    }
}
